/*global jQuery*/
(function($) {
	/**
	 * jQuery Unused Styles plugin
	 * 
	 * Displays a debug toolbar in the top right corner of the page.
	 * Hover on individual rules displays the origin of that rule.
	 * The order of the rules is consistent with the order of applied
	 * rules according to the document.
	 * 
	 * Currently only works on Firefox.
	 * 
	 * Known issues with other browsers:
	 *  - Chrome treats external stylesheets on local file system as security exception
	 *  - IE treats all <link> and <style> tags as off limits
	 * 
	 */
	
	var widget, title, reloadButton, rulesList;
	
	var getRules = function() {
		var rules = [];
		for(var i = 0; i < document.styleSheets.length; i++) {
			var sheet = document.styleSheets[i];
			try {
				var ruleCollection = sheet.cssRules || sheet.rules;
				for(var j = 0; j < ruleCollection.length; j++) {
					if(sheet.ownerNode && sheet.ownerNode.nodeName) {
						switch(sheet.ownerNode.nodeName.toLowerCase()) {
							case "style":
								rules.push({ selector: ruleCollection[j].selectorText, sheet: "Embedded" });
								break;
							case "link":
								rules.push({ selector: ruleCollection[j].selectorText, sheet: "Link (" + sheet.href + ")" });
								break;
						}
					} else {
						rules.push({selector: ruleCollection[j].selectorText, sheet: "Cannot determine source (IE?)"});
					}
				}
			} catch(ex) {
				/* If a console is present, debug or log the exception, else silently ignore */
				if(console && console.debug) console.debug("Exception: ", ex);
				else if(console && console.log) console.log("Exception: " + ex.message);
			}
		}
		return rules;
	};
	
	var appendStylesheet = function(path, id) {
		if(id === undefined) {
			$("head").append('<link rel="stylesheet" type="text/css" href="' + path + '"/>');
		} else {
			$("head").append('<link rel="stylesheet" type="text/css" href="' + path + '" id="' + id + '"/>');
		}
	};
	
	var refreshList = function(params) {
		$("link#" + params.linkId).remove();
		rulesList.children().remove();
		var rules = getRules();
		for(var k = 0; k < rules.length; k++) {
			if($(rules[k].selector).length === 0) {
				rulesList.append('<li title="' + rules[k].sheet + '">' + rules[k].selector + '</li>');
			}
		}
		appendStylesheet(params.cssHref, params.linkId);
	};
	
	var init = function(params) {
		var p = $.extend({}, $.unusedStyles.defaults, params);
		widget = $('<div id="unused-styles"/>').appendTo("body");
		title = $('<h1>&raquo; Unused rules</h1>').appendTo(widget);
		reloadButton = $('<img src="' + p.imageHref + '" alt="" title="Reload"/>').appendTo(title).click(function() { refreshList(p); });
		rulesList = $('<ul/>').appendTo(widget);
		refreshList(p);
	};
	
	$.extend({
		unusedStyles: init
	});

	$.unusedStyles.defaults = {
		cssHref: "jquery.unused.css",
		imageHref: "reload.png",
		linkId: "unusedStylesStyleSheet"
	};
})(jQuery);